package com.xiaocq.wordskiller.fileIO;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.sql.Connection;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.xiaocq.wordskiller.db.DatabaseHelper;
import com.xiaocq.wordskiller.db.VocabularyDatabase.VocabularyMeta;

public class Test {
	private static final String TAG = "WordsReader";
	private Context context;

	public Test(Context context) {

		this.context = context;
	}

	public void writeIntoDatabase(InputStream inputStream) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream));
		DatabaseHelper mOpenHelper = new DatabaseHelper(context);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		String[] fileds;
		String sql = "INSERT INTO " + VocabularyMeta.TABLE_NAME + " ("
				+ VocabularyMeta.VOCABULARY + "," + VocabularyMeta.EXPLAIN
				+ "," + VocabularyMeta.TEST_COUNT + ","
				+ VocabularyMeta.CORRECT_COUNT + ","
				+ VocabularyMeta.ANSWER_STATE + "," + VocabularyMeta.BELONG_TO
				+ "," + VocabularyMeta.LEAST_ACCESS + ") VALUES(?,?,0,0,0,?,0)";
		Log.d(TAG, sql);
		try {
			db.beginTransaction();
			while (reader.ready()) {
				fileds = reader.readLine().split("@");
				db.execSQL(sql, fileds);
			}
			db.setTransactionSuccessful();
			reader.close();
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
			db.close();
			mOpenHelper.close();
		}
	}

	public int[] getDetailOfTest(FileInputStream inputStream, int size) {
		int[] result = new int[size];
		String encoding = "UTF-8";
		int index = 0;
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, encoding);
			BufferedReader reader = new BufferedReader(inputStreamReader);
			while (reader.ready()) {
				result[index++] = Integer.valueOf(reader.readLine());
			}
			reader.close();
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public boolean writeIntoInternalFile(FileOutputStream outputStream,
			int[] details) {
		String encoding = "UTF-8";
		int length = details.length;
		try {
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
					outputStream, encoding);
			BufferedWriter writer = new BufferedWriter(outputStreamWriter);
			for (int i = 0; i < length; i++) {
				if (details[i] != 0) {
					writer.write(Integer.toString(details[i]));
					System.out.println(details[i]);
					writer.newLine();
				}
			}
			writer.flush();
			writer.close();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
